import { isMobile } from '@/utils'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { storage } from '@/utils/storage'
import { useRouter } from 'vue-router'
import router from '@/router'

const state = () => ({
  isMobile: isMobile(),
  token: storage.get(ACCESS_TOKEN) || '',
  userInfo: storage.get(USER_INFO) || {},
  activeMenu: storage.get('activeMenu') || [],
})

// getters
const getters = {
  state: (state) => state.isMobile,
  token: (state) => state.token,
}

// mutations
const mutations = {
  SET_MOBILE_STATE(state, val) {
    state.isMobile = val
  },
  SET_TOKEN(state, val) {
    state.token = val
    storage.set(ACCESS_TOKEN, val)
  },
  SET_USERINFO(state, val) {
    state.userInfo = val
    storage.set(USER_INFO, val)
  },
  SET_ACTIVE_MENU(state, val) {
    state.activeMenu = val
    storage.set('activeMenu', val)
  },
}

// actions
const actions = {
  logout({ commit, state }) {
    commit('SET_TOKEN', '')
    commit('SET_ACTIVE_MENU', [])
    commit('SET_USERINFO', {})
    storage.clear()
    router.replace({ path: '/user/login' })
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
}
